package com.itany.corejava.code16_反射;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月12日16:16
 */
public class Test06_解析注解 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        Class c=Student.class;
        // 1.获取类上的注解
        Annotation[] annotations=c.getAnnotations();
        System.out.println(Arrays.toString(annotations));

        // 2.获取类上的指定的注解
        Annotation annotation=c.getAnnotation(SomeAnnotation.class);
        System.out.println(annotation);
        annotation=c.getAnnotation(OtherAnnotation.class);
        System.out.println(annotation);

        // 3.获取属性上的所有注解
        Field nameField=c.getDeclaredField("name");
        annotations=nameField.getDeclaredAnnotations();
        System.out.println(Arrays.toString(annotations));

        //4.获取属性上的指定注解
        annotation=nameField.getAnnotation(SomeAnnotation.class);
        System.out.println(annotation);

        //5.获取方法上的所有注解
        Method method=c.getDeclaredMethod("study");
        annotations=method.getAnnotations();
        System.out.println(Arrays.toString(annotations));

        // 6.获取方法上指定注解
        annotation=method.getAnnotation(OtherAnnotation.class);
        System.out.println(annotation);

        // 7.获取指定注解中指定属性的值
       if(annotation instanceof OtherAnnotation){
            OtherAnnotation otherAnnotation= (OtherAnnotation) annotation;
           System.out.println("encoding:"+otherAnnotation.encoding());
           System.out.println("method:"+Arrays.toString(otherAnnotation.method()));
       }
       annotation=method.getAnnotation(SomeAnnotation.class);
       if(annotation instanceof SomeAnnotation){
            SomeAnnotation someAnnotation= (SomeAnnotation) annotation;
           System.out.println("value:"+Arrays.toString(someAnnotation.value()));
       }


       Field ageField=c.getDeclaredField("age");
       if(ageField.isAnnotationPresent(SomeAnnotation.class)){
            SomeAnnotation someAnnotation=ageField.getAnnotation(SomeAnnotation.class);
            System.out.println(someAnnotation.name());
       }else{
           System.out.println("age属性中没有使用SomeAnnotation注解");
       }

    }
}
